{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "-OtKP_x_xTE6"
   },
   "source": [
    "# 残差网络（ResNet）\n",
    "\n",
    "让我们先思考一个问题：对神经网络模型添加新的层，充分训练后的模型是否只可能更有效地降低训练误差？理论上，原模型解的空间只是新模型解的空间的子空间。也就是说，如果我们能将新添加的层训练成恒等映射$f(x) = x$，新模型和原模型将同样有效。由于新模型可能得出更优的解来拟合训练数据集，因此添加层似乎更容易降低训练误差。然而在实践中，添加过多的层后训练误差往往不降反升。即使利用批量归一化带来的数值稳定性使训练深层模型更加容易，该问题仍然存在。针对这一问题，何恺明等人提出了残差网络（ResNet） [1]。它在2015年的ImageNet图像识别挑战赛夺魁，并深刻影响了后来的深度神经网络的设计。\n",
    "\n",
    "\n",
    "## 残差块\n",
    "\n",
    "让我们聚焦于神经网络局部。如图5.9所示，设输入为$\\boldsymbol{x}$。假设我们希望学出的理想映射为$f(\\boldsymbol{x})$，从而作为图5.9上方激活函数的输入。左图虚线框中的部分需要直接拟合出该映射$f(\\boldsymbol{x})$，而右图虚线框中的部分则需要拟合出有关恒等映射的残差映射$f(\\boldsymbol{x})-\\boldsymbol{x}$。残差映射在实际中往往更容易优化。以本节开头提到的恒等映射作为我们希望学出的理想映射$f(\\boldsymbol{x})$。我们只需将图5.9中右图虚线框内上方的加权运算（如仿射）的权重和偏差参数学成0，那么$f(\\boldsymbol{x})$即为恒等映射。实际中，当理想映射$f(\\boldsymbol{x})$极接近于恒等映射时，残差映射也易于捕捉恒等映射的细微波动。图5.9右图也是ResNet的基础块，即残差块（residual block）。在残差块中，输入可通过跨层的数据线路更快地向前传播。\n",
    "\n",
    "![设输入为$\\boldsymbol{x}$。假设图中最上方激活函数输入的理想映射为$f(\\boldsymbol{x})$。左图虚线框中的部分需要直接拟合出该映射$f(\\boldsymbol{x})$，而右图虚线框中的部分需要拟合出有关恒等映射的残差映射$f(\\boldsymbol{x})-\\boldsymbol{x}$](../img/residual-block.svg)\n",
    "\n",
    "ResNet沿用了VGG全$3\\times 3$卷积层的设计。残差块里首先有2个有相同输出通道数的$3\\times 3$卷积层。每个卷积层后接一个批量归一化层和ReLU激活函数。然后我们将输入跳过这两个卷积运算后直接加在最后的ReLU激活函数前。这样的设计要求两个卷积层的输出与输入形状一样，从而可以相加。如果想改变通道数，就需要引入一个额外的$1\\times 1$卷积层来将输入变换成需要的形状后再做相加运算。\n",
    "\n",
    "残差块的实现如下。它可以设定输出通道数、是否使用额外的$1\\times 1$卷积层来修改通道数以及卷积层的步幅。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "pb3EjdQjxUlB"
   },
   "outputs": [],
   "source": [
    "import d2ltorch as d2lt\n",
    "import torch\n",
    "from torch import nn, optim\n",
    "from torchsummary import summary_depth\n",
    "\n",
    "class Residual(nn.Module): # 本类已保存在d2ltorch包中方便以后使用\n",
    "    def __init__(self, in_channels, out_channels, use_1x1conv=False, stride=1, **kwargs):\n",
    "        super(Residual, self).__init__(**kwargs)\n",
    "        self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1, \n",
    "                               stride=stride)\n",
    "        self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1)\n",
    "        if use_1x1conv:\n",
    "            self.conv3 = nn.Conv2d(in_channels, out_channels, kernel_size=1,\n",
    "                                  stride=stride)\n",
    "        else:\n",
    "            self.conv3 = None\n",
    "        self.bn1 = nn.BatchNorm2d(out_channels)\n",
    "        self.bn2 = nn.BatchNorm2d(out_channels)\n",
    "        \n",
    "    def forward(self, X):\n",
    "        Y = torch.relu(self.bn1(self.conv1(X)))\n",
    "        Y = self.bn2(self.conv2(Y))\n",
    "        if self.conv3:\n",
    "            X = self.conv3(X)\n",
    "        return torch.relu(Y + X)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "pO4qUiBnxYAv"
   },
   "source": [
    "下面我们来查看输入和输出形状一致的情况。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 35
    },
    "colab_type": "code",
    "id": "FXoCCl7txabO",
    "outputId": "c03cbab0-2f36-4f9a-b293-3f8596bdb69b"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "torch.Size([4, 3, 6, 6])"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "blk = Residual(3, 3)\n",
    "X = torch.rand(4, 3, 6, 6)\n",
    "blk(X).shape"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "87CWi0N0xce7"
   },
   "source": [
    "我们也可以在增加输出通道数的同时减半输出的高和宽。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 35
    },
    "colab_type": "code",
    "id": "9a-BgZPdxe2J",
    "outputId": "3ba31205-5478-4dc6-cb2e-5d90b4782442"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "torch.Size([4, 6, 3, 3])"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "blk = Residual(3, 6, use_1x1conv=True, stride=2)\n",
    "blk(X).shape"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "4EHC_ItyxjvY"
   },
   "source": [
    "## ResNet模型\n",
    "\n",
    "ResNet与之前介绍的GoogleLeNet的结构类似，与GoogLeNet中4个由Inception块组成的模块对应，ResNet使用4个由残差块组成的模块，每个模块使用若干个同样输出通道数的残差块。第一个模块的通道数同输入通道数一致。由于之前已经使用了步幅为2的最大池化层，所以无须减小高和宽。之后的每个模块在第一个残差块里将上一个模块的通道数翻倍，并将高和宽减半。\n",
    "\n",
    "下面我们来实现这个模块。注意，这里对第一个模块做了特别处理。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "LcFYjBp2xkqE"
   },
   "outputs": [],
   "source": [
    "def resnet_block(in_channels, out_channels, num_residuals, first_block=False):\n",
    "    blk = []\n",
    "    for i in range(num_residuals):\n",
    "        if i == 0:\n",
    "            if not first_block:\n",
    "                blk.append(Residual(in_channels, out_channels, use_1x1conv=True, stride=2))\n",
    "            else:\n",
    "                blk.append(Residual(in_channels, out_channels))\n",
    "        else:\n",
    "            blk.append(Residual(out_channels, out_channels))\n",
    "    return nn.Sequential(*blk)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "lugSSFnZxvZW"
   },
   "source": [
    "下面仿照GoogLeNet实现ResNet。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "AVB9fnKyx2DF"
   },
   "outputs": [],
   "source": [
    "class MyResNet(nn.Module):\n",
    "    def __init__(self, in_channels, **kwargs):\n",
    "        super(MyResNet, self).__init__(**kwargs)\n",
    "        \n",
    "        # ResNet的前两层跟之前介绍的GoogLeNet中的一样：在输出通道数为64、\n",
    "        # 步幅为2的 7 x 7卷积层后接步幅为2的 3 x 3 的最大池化层。\n",
    "        # 不同之处在于ResNet每个卷积层后增加的批量归一化层。\n",
    "        self.b1 = nn.Sequential(\n",
    "            nn.Conv2d(in_channels, 64, kernel_size=7, stride=2, padding=3),\n",
    "            nn.BatchNorm2d(64), nn.ReLU(),\n",
    "            nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n",
    "        )\n",
    "        \n",
    "        # 接着我们为ResNet加入所有残差块。这里每个模块使用两个残差块。\n",
    "        # 然后加一个全局平均池化层调整大小\n",
    "        self.b2 = nn.Sequential(\n",
    "            resnet_block(64, 64, 2, first_block=True),\n",
    "            resnet_block(64, 128, 2),\n",
    "            resnet_block(128, 256, 2),\n",
    "            resnet_block(256, 512, 2),\n",
    "            nn.AdaptiveAvgPool2d((1, 1))\n",
    "        )\n",
    "        \n",
    "        # 最后，与GoogLeNet一样，接上全连接层输出。\n",
    "        self.output = nn.Linear(512*1*1, 10)\n",
    "    \n",
    "    def forward(self, x):\n",
    "        x = self.b1(x)\n",
    "        x = self.b2(x)\n",
    "        x = x.reshape(-1, 512*1*1)\n",
    "        x = self.output(x)\n",
    "        return x"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "a_Zxs9ufx7y2"
   },
   "source": [
    "这里每个模块里有4个卷积层（不计算$1\\times 1$卷积层），加上最开始的卷积层和最后的全连接层，共计18层。这个模型通常也被称为ResNet-18。通过配置不同的通道数和模块里的残差块数可以得到不同的ResNet模型，例如更深的含152层的ResNet-152。虽然ResNet的主体架构跟GoogLeNet的类似，但ResNet结构更简单，修改也更方便。这些因素都导致了ResNet迅速被广泛使用。\n",
    "\n",
    "在训练ResNet之前，我们来观察一下输入形状在ResNet不同模块之间的变化。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 1092
    },
    "colab_type": "code",
    "id": "TsT4ldm1x8qD",
    "outputId": "b6e5097e-3546-47e6-b97c-e9cdee24de57"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "------------------------------------------------------------------------------------------\n",
      "Layer (type:depth-idx)                   Output Shape              Param #        \n",
      "==========================================================================================\n",
      "├─Sequential: 1-1                        [-1, 64, 56, 56]          --             \n",
      "|    └─Conv2d: 2-1                       [-1, 64, 112, 112]        3,200          \n",
      "|    └─BatchNorm2d: 2-2                  [-1, 64, 112, 112]        128            \n",
      "|    └─ReLU: 2-3                         [-1, 64, 112, 112]        --             \n",
      "|    └─MaxPool2d: 2-4                    [-1, 64, 56, 56]          --             \n",
      "├─Sequential: 1-2                        [-1, 512, 1, 1]           --             \n",
      "|    └─Sequential: 2-5                   [-1, 64, 56, 56]          --             \n",
      "|    |    └─Residual: 3-1                [-1, 64, 56, 56]          --             \n",
      "|    |    └─Residual: 3-2                [-1, 64, 56, 56]          --             \n",
      "|    └─Sequential: 2-6                   [-1, 128, 28, 28]         --             \n",
      "|    |    └─Residual: 3-3                [-1, 128, 28, 28]         --             \n",
      "|    |    └─Residual: 3-4                [-1, 128, 28, 28]         --             \n",
      "|    └─Sequential: 2-7                   [-1, 256, 14, 14]         --             \n",
      "|    |    └─Residual: 3-5                [-1, 256, 14, 14]         --             \n",
      "|    |    └─Residual: 3-6                [-1, 256, 14, 14]         --             \n",
      "|    └─Sequential: 2-8                   [-1, 512, 7, 7]           --             \n",
      "|    |    └─Residual: 3-7                [-1, 512, 7, 7]           --             \n",
      "|    |    └─Residual: 3-8                [-1, 512, 7, 7]           --             \n",
      "|    └─AdaptiveAvgPool2d: 2-9            [-1, 512, 1, 1]           --             \n",
      "├─Linear: 1-3                            [-1, 10]                  5,130          \n",
      "==========================================================================================\n",
      "Total params: 11,178,378\n",
      "Trainable params: 11,178,378\n",
      "Non-trainable params: 0\n",
      "------------------------------------------------------------------------------------------\n",
      "Input size (MB): 0.19\n",
      "Params size (MB): 42.64\n",
      "------------------------------------------------------------------------------------------\n"
     ]
    }
   ],
   "source": [
    "net = MyResNet(in_channels=1)\n",
    "summary_depth(net, (1, 224, 224), device='cpu')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "yCOyBmIox-8Y"
   },
   "source": [
    "## 获取数据和训练模型\n",
    "\n",
    "下面我们在Fashion-MNIST数据集上训练ResNet。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 121
    },
    "colab_type": "code",
    "id": "dZk-uF-ZyCAM",
    "outputId": "a29f3e39-6fb2-49b4-9227-a27333af37bd"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "training on cuda:0\n",
      "epoch 1, loss 0.0020, train acc 0.826, test acc 0.836, time 20.2 sec\n",
      "epoch 2, loss 0.0010, train acc 0.904, test acc 0.891, time 20.3 sec\n",
      "epoch 3, loss 0.0008, train acc 0.928, test acc 0.831, time 20.3 sec\n",
      "epoch 4, loss 0.0006, train acc 0.946, test acc 0.810, time 20.7 sec\n",
      "epoch 5, loss 0.0004, train acc 0.959, test acc 0.893, time 20.5 sec\n"
     ]
    }
   ],
   "source": [
    "root = '~/dataset/'\n",
    "lr, num_epochs, batch_size, device = 0.05, 5, 256, d2lt.try_gpu()\n",
    "\n",
    "d2lt.params_init(net, init=nn.init.xavier_uniform_)\n",
    "\n",
    "optimizer = optim.SGD(net.parameters(), lr=lr)\n",
    "train_iter, test_iter = d2lt.load_data_fashion_mnist(root, batch_size, resize=96)\n",
    "d2lt.train_ch5(net, train_iter, test_iter, batch_size, optimizer, device,\n",
    "              num_epochs)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "st0NiuHUySpp"
   },
   "source": [
    "## 小结\n",
    "\n",
    "* 残差块通过跨层的数据通道从而能够训练出有效的深度神经网络。\n",
    "* ResNet深刻影响了后来的深度神经网络的设计。\n",
    "\n",
    "\n",
    "## 练习\n",
    "\n",
    "* 参考ResNet论文的表1来实现不同版本的ResNet [1]。\n",
    "* 对于比较深的网络， ResNet论文中介绍了一个“瓶颈”架构来降低模型复杂度。尝试实现它 [1]。\n",
    "* 在ResNet的后续版本里，作者将残差块里的“卷积、批量归一化和激活”结构改成了“批量归一化、激活和卷积”，实现这个改进（[2]，图1）。\n",
    "\n",
    "\n",
    "\n",
    "## 参考文献\n",
    "\n",
    "[1] He, K., Zhang, X., Ren, S., & Sun, J. (2016). Deep residual learning for image recognition. In Proceedings of the IEEE conference on computer vision and pattern recognition (pp. 770-778).\n",
    "\n",
    "[2] He, K., Zhang, X., Ren, S., & Sun, J. (2016, October). Identity mappings in deep residual networks. In European Conference on Computer Vision (pp. 630-645). Springer, Cham.\n",
    "\n",
    "## 扫码直达[讨论区](https://discuss.gluon.ai/t/topic/1663)\n",
    "\n",
    "![](../img/qr_resnet.svg)"
   ]
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "collapsed_sections": [],
   "name": "resnet.ipynb",
   "provenance": [],
   "version": "0.3.2"
  },
  "kernelspec": {
   "display_name": "Python [conda env:pytorch]",
   "language": "python",
   "name": "conda-env-pytorch-py"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.9"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
